package net.pzc.filechooser;

import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.io.File;
import java.io.FileFilter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.SwingUtilities;

public class ListFilesAction extends Thread {

	private JComponent ui = null;
	private DefaultListModel listModel = null;
	private FileItemTableModel tableModel = null;
	private String path = null;
	private FileFilter fileFilter = null;

	private FastFileChooser chooser = null;

	private boolean requestStop = false;

	private static long SIZE_KB = 1024;
	private static long SIZE_MB = SIZE_KB * SIZE_KB;

	public ListFilesAction(JComponent ui, FastFileChooser chooser, String path) {
		this.ui = ui;
		this.chooser = chooser;
		this.path = path;
		chooser.getTxt_fileName().setText("");
		this.fileFilter = (FileFilter) chooser.getCmb_fileType().getSelectedItem();
		chooser.getCmb().setEnabled(false);
		chooser.getBtn_up().setEnabled(false);
		ui.setEnabled(false);
		ui.setBackground(new Color(212, 208, 200));
		chooser.getCmb_fileType().setEnabled(false);
		chooser.getBtn_open().setEnabled(false);
		for (Component comp : chooser.getJpUserHome().getComponents()) {
			comp.setEnabled(false);
		}
		ui.getParent().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
		if (ui instanceof JList) {
			this.listModel = (DefaultListModel) ((JList) ui).getModel();
		} else if (ui instanceof JTable) {
			this.tableModel = (FileItemTableModel) ((JTable) ui).getModel();
		}
	}

	@Override
	public void run() {

		try {
			startWork();
		} catch (Exception e) {
			e.printStackTrace();
		}

		// FileSystemView sysView = FileSystemView.getFileSystemView();
		File initFile = new File(path);
		if (initFile.exists() == false) {
			String desktopPath = System.getProperty("user.home") + "/Desktop";
			initFile = new File(desktopPath);
		}
		File[] roots = null;
		if (this.fileFilter != null) {
			roots = initFile.listFiles(this.fileFilter);
		} else {
			roots = initFile.listFiles();
		}
		if (chooser.getMode() == FastFileChooser.MODE_FOLDER) {
			List<File> dirList = new ArrayList<File>();
			for (int i = 0; i < roots.length; i++) {
				if (roots[i].isDirectory() == true) {
					dirList.add(roots[i]);
				}
			}
			roots = dirList.toArray(new File[] {});
		}
		if (roots != null) {
			try {
				initProgressBar(roots.length);
			} catch (Exception e) {
				e.printStackTrace();
			}
			for (int i = 0; i < roots.length; i++) {
				if (requestStop) {
					break;
				}
				File file = roots[i];

				FileItem fi = new FileItem();

				FastFileChooser.make(file, fi, true);

				long size = -1;
				String strSize = "";
				if (file.isFile()) {
					size = file.length();
					if (size < SIZE_KB) {
						strSize = String.valueOf(size) + "B";
					} else if (size >= SIZE_KB && size < SIZE_MB) {
						DecimalFormat myformat = new DecimalFormat("0.##");
						strSize = String.valueOf(myformat.format((double) size / SIZE_KB)) + "KB";
					} else if (size >= SIZE_MB) {
						DecimalFormat myformat = new DecimalFormat("0.##");
						strSize = String.valueOf(myformat.format((double) size / SIZE_MB)) + "MB";
					}
				}

				fi.setAbsolutePath(file.getAbsolutePath());
				fi.setName(file.getName());
				fi.setSize(strSize);
				fi.setUpdDatetime(new Date(file.lastModified()).toLocaleString());

				// ImageIO.write(img, "PNG", new File("C:/xxx/" + i + ".png"));

				try {
					updateUI(fi, i + 1);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		try {
			finishWork();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void startWork() throws Exception {
		SwingUtilities.invokeAndWait(new Runnable() {

			public void run() {
				if (listModel != null) {
					listModel.clear();
				} else if (tableModel != null) {
					tableModel.clear();
				}
			}

		});
	}

	private void initProgressBar(final int max) throws Exception {
		SwingUtilities.invokeAndWait(new Runnable() {

			public void run() {
				chooser.getProgressBar().setMaximum(max);
				chooser.getProgressBar().setString("0/" + max);
			}

		});
	}

	private void updateUI(final FileItem fi, final int i) throws Exception {
		SwingUtilities.invokeAndWait(new Runnable() {

			public void run() {
				if (listModel != null) {
					listModel.addElement(fi);
				} else if (tableModel != null) {
					// tableModel.addRow(rowData);
					// tableModel.get
					tableModel.addRow(fi);
				}
				chooser.getProgressBar().setValue(i);
				chooser.getProgressBar().setString(i + "/" + chooser.getProgressBar().getMaximum());
			}

		});
	}

	private void finishWork() throws Exception {
		SwingUtilities.invokeAndWait(new Runnable() {

			public void run() {
				if (requestStop) {
					chooser.updateStatus("stop scan");
				}
				ui.getParent().setCursor(Cursor.getDefaultCursor());
				chooser.getCmb().setEnabled(true);
				chooser.getBtn_up().setEnabled(true);
				for (Component comp : chooser.getJpUserHome().getComponents()) {
					comp.setEnabled(true);
				}
				ui.setEnabled(true);
				ui.setBackground(Color.white);
				chooser.getCmb_fileType().setEnabled(true);
			}

		});
	}

	public void requestStopScan() {
		requestStop = true;
	}
}
